<template>
  <div ref="container" style="height: 100vh">
    <button @click="update">更新</button>
    <button @click="add">添加</button>
    <button @click="remove">删除</button>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {select} from "d3";

const container = ref(null)

const list = [
  {key: 0, data: Math.random()},
  {key: 1, data: Math.random()},
  {key: 2, data: Math.random()},
  {key: 3, data: Math.random()},
]

let selection, key = 3

function getSelection() {
  return select(container.value)
    .selectAll('h1')
    .data(list, d => d.key)
}

onMounted(() => {

  selection = getSelection()

  selection = selection.enter()
    .append('h1')
    .text(d => d.data)
})

function update() {
  const item = list.find(v => v.key === key)
  item.data = Math.random()
  selection.text(d => d.data)
}

function add() {
  key += 1
  list.push({
    key,
    data: Math.random()
  })

  selection = getSelection()
  console.log(selection)
  // const enterSelection = selection.enter()
  //     .append('h1')
  //     .text(d => d.data)
  //
  // selection = selection.merge(enterSelection)

}

function remove() {
  list.shift()

  selection = getSelection()

  selection.exit().remove()

  const enter = selection.enter()
    .append('h1')
    .text(d => {
      console.log(d)
      return d.data
    })

  console.log(enter)

  selection.merge(enter)
}
</script>

<style scoped lang="less">

</style>
